﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Text;
using System;
public class Root : MonoBehaviour
{
    NetClient Net;
    void Start()
    {
        this.Net = new NetClient(this.OnPackageHandler);
        this.Net.Connected += Net_Connected;
        this.Net.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4399));

      
     
    }

    private void Net_Connected(object sender, System.EventArgs e)
    {
        this.SendString(0,"yangdao卡鲁宾");
    }

    void SendString(int msgId,string str)
    {
        byte[] stringData = Encoding.UTF8.GetBytes(str);

        var lenData = System.BitConverter.GetBytes(IPAddress.HostToNetworkOrder(stringData.Length+2));

        byte[] IdData = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((System.Int16)msgId));
   
        byte[] sendData = new byte[4 + 2 + stringData.Length];

        System.Array.Copy(lenData, sendData, 4);
        System.Array.Copy(IdData, 0,sendData, 4,IdData.Length);
        System.Array.Copy(stringData, 0, sendData, 6, stringData.Length);
        this.Net.Send(sendData);
    }

    void OnPackageHandler(IPackageInfo packageInfo)
    {
        DataEventArgs data = ((PackageInfo)packageInfo).Data;
        byte[] recvData = new byte[data.Length];
        System.Array.Copy(data.Data,data.Offset+6,recvData,0,data.Length);
        Debug.Log(Encoding.UTF8.GetString(recvData));
    }
    void OnApplicationQuit()
    {
        if (this.Net != null)
        {
            this.Net.Close();
        }
    }

}
